﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CoolERP_Entities;
using CoolERP_BLL;

namespace CoolERP_Web.User
{
    public partial class PermissionAssign : BasePage
    {
        protected Guid RoleId
        {
            get { return this.GetUrlParam("rid") == null ? Guid.Empty : new Guid(this.GetUrlParam("rid").ToString()); }
        }
        protected Guid UserId
        {
            get { return this.GetUrlParam("uid") == null ? Guid.Empty : new Guid(this.GetUrlParam("uid").ToString()); }
        }
        protected string strName
        {
            get { return this.GetUrlParam("name") == null ? "" : this.GetUrlParam("name").ToString(); }
        }
        private List<RolePermissions> rolePermissions;
        private bool AllCheck
        {
            get { return this.ViewState["AllCheck"] == null ? true : Convert.ToBoolean(this.ViewState["AllCheck"]); }
            set { this.ViewState["AllCheck"] = value; }
        }
        private List<Guid> RoleIdList
        {
            get { return this.ViewState["RoleIdList"] == null ? null : (List<Guid>)this.ViewState["RoleIdList"]; }
            set { this.ViewState["RoleIdList"] = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            AllCheck = true;
            if (!IsPostBack)
            {
                RoleIdList = new List<Guid>();
                if (!string.IsNullOrEmpty(strName))
                    this.lbTitle.Text = "分配权限到角色：" + strName;
                else
                    this.lbTitle.Text = "分配权限到角色";
                if (RoleId != Guid.Empty)
                    RoleIdList.Add(RoleId);
                if (UserId != Guid.Empty)
                {
                    using (UserInRolesBLL uBLL = new UserInRolesBLL())
                    {
                        RoleIdList.AddRange(uBLL.GetList(t => t.UserId == UserId).Select(t => t.RoleId).ToList());
                        if (!string.IsNullOrEmpty(strName))
                            this.lbTitle.Text = "分配权限到用户：" + strName;
                        else
                            this.lbTitle.Text = "分配权限到用户";
                    }
                    btnReturn.PostBackUrl = "~/User/UserManage.aspx";
                }
                this.AspNetPager1.PageSize = GridView1.PageSize;
                BindGridview();
            }
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Permissions entity = e.Row.DataItem as Permissions;
                CheckBox cb = e.Row.FindControl("cbAssign") as CheckBox;
                cb.Checked = RoleHasPermisison(entity.Id);
                if (!cb.Checked)
                    AllCheck = false;
                cb.Attributes.Add("value", entity.Id.ToString());
            }
        }

        private bool RoleHasPermisison(Guid permisisonId)
        {
            foreach (var rp in rolePermissions)
            {
                if (rp.PermissionId.Equals(permisisonId))
                    return true;
            }
            return false;
        }

        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            BindGridview();
            lbResult.Text = "";
        }

        private void BindGridview()
        {
            using (RolePermissionsBLL dao = new RolePermissionsBLL())
            {
                rolePermissions = dao.GetList(t => RoleIdList.Contains(t.RoleId));
            }
            int RecordCount = 0;            
            using (PermissionsBLL pBLL = new PermissionsBLL())
            {
                List<Permissions> itemLists = pBLL.GetPagerList(null, "Code asc", this.AspNetPager1.CurrentPageIndex, this.AspNetPager1.PageSize, out RecordCount);
                GridView1.DataSource = itemLists;
                GridView1.DataBind();
            }
            this.AspNetPager1.RecordCount = RecordCount;
            this.AspNetPager1.Visible = RecordCount > 0;
            panMsg.Visible = !this.AspNetPager1.Visible;
            CheckBox cbAll = GridView1.HeaderRow.FindControl("cbAll") as CheckBox;
            cbAll.Checked = AllCheck;            
        }

        protected void cbAll_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox cb = (sender as CheckBox);
            bool res = false;
            List<Guid> perIds = new List<Guid>();
            foreach (GridViewRow container in GridView1.Rows)
            {
                CheckBox cBox = (CheckBox)container.FindControl("cbAssign");
                perIds.Add(new Guid(cBox.Attributes["value"]));
            }
            using (RolePermissionsBLL rBLL = new RolePermissionsBLL())
            {
                List<RolePermissions> items = new List<RolePermissions>();
                if (cb.Checked)
                {
                    foreach (var id in perIds)
                    {
                        foreach (var rid in RoleIdList)
                        {
                            RolePermissions rp = rBLL.GetEntity(t => t.PermissionId == id && t.RoleId == rid);
                            if (rp == null)
                            {
                                rp = new RolePermissions();
                                rp.PermissionId = id;
                                rp.RoleId = RoleId;
                                rp.Access = 1;
                                items.Add(rp);
                            }
                        }
                    }
                    res = rBLL.Inserts(items);
                }
                else
                {
                    foreach (var id in perIds)
                    {
                        foreach (var rid in RoleIdList)
                        {
                            RolePermissions rp = rBLL.GetEntity(t => t.RoleId == rid && t.PermissionId == id);
                            if (rp != null)
                                items.Add(rp);
                        }
                    }
                    res = rBLL.Deletes(items);
                }
            }
            if (res == true)
                lbResult.Text = "更新角色的权限成功";
            else
                lbResult.Text = "更新角色的权限失败";
            BindGridview();
        }

        protected void cbAssign_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox cb = (sender as CheckBox);
            Guid pid = new Guid(cb.Attributes["value"]);
            bool res = false;
            using (RolePermissionsBLL dao = new RolePermissionsBLL())
            {
                List<RolePermissions> items = new List<RolePermissions>();
                if (cb.Checked)
                {
                    foreach (var rid in RoleIdList)
                    {
                        RolePermissions rp = new RolePermissions();
                        rp.PermissionId = pid;
                        rp.RoleId = rid;
                        rp.Access = 1;
                        items.Add(rp);
                    }
                    res = dao.Inserts(items);
                }
                else
                {
                    foreach (var rid in RoleIdList)
                    {
                        RolePermissions rp = dao.GetEntity(t => t.RoleId == rid && t.PermissionId == pid);
                        items.Add(rp);
                    }
                    res = dao.Deletes(items);
                }
            }
            if (res == true)
                lbResult.Text = "更新角色的权限成功";
            else
                lbResult.Text = "更新角色的权限失败";
            BindGridview();
        }
    }
}